#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
#include "../include/database.h"

static sqlite3 *db = NULL;

int initialize_database() {
    int rc = sqlite3_open(DB_NAME, &db);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "无法打开数据库: %s\n", sqlite3_errmsg(db));
        return rc;
    }

    const char *sql = "CREATE TABLE IF NOT EXISTS users ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                      "username TEXT NOT NULL UNIQUE,"
                      "password TEXT NOT NULL);";

    return execute_sql(sql, NULL, NULL);
}

int close_database(sqlite3 *db) {
    return sqlite3_close(db);
}

int execute_sql(const char *sql, int (*callback)(void*,int,char**,char**), void *data) {
    char *err_msg = 0;
    int rc = sqlite3_exec(db, sql, callback, data, &err_msg);
    
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", err_msg);
        sqlite3_free(err_msg);
    }
    
    return rc;
}